package cn.com.filemanager;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author zhaokk
 * @since 2024/7/20
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        if(StringUtils.isBlank(name)){
            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return;
        }
        File file = new File(SystemConfig.getConfig().get("upload_path") + name);
        //读取服务器本地的文件
        FileInputStream in = new FileInputStream(file);
        /**
         * 处理URL编码问题
         */
        String fileName = file.getName();
        //对文件名进行URl编码
        fileName = URLEncoder.encode(fileName, "utf-8");

        //判断不同浏览器
        String userAgent = req.getHeader("user-agent");
        String filefix = null;
        if (userAgent.contains("Trident")) {
            //IE
            filefix = "filename=" + fileName;
        } else if (userAgent.contains("Firefox")) {
            //Firefox
            filefix = "filename*=" + fileName;
        } else {
            filefix = "filename=" + fileName;
        }

        //告诉浏览器以下载方式打开资源
        resp.setHeader("Content-Disposition", "attachment;" + filefix);
        //把本地文件发送给浏览器
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            resp.getOutputStream().write(buf, 0, len);
        }
        //关闭
        in.close();
    }

}
